#pragma once
#include <fstream>
#include <cstdint>
#include <stdexcept>
#include <bitset>
#include <iostream>

// 读取 nByte（1~8）的二进制小端整数
inline uint64_t readLE(std::ifstream* fin, size_t nByte) {
    if (nByte == 0 || nByte > 8)
        throw std::invalid_argument("readLE: nByte must be 1~8");

    char buf[8]{}; // 最大 8 字节
    fin->read(buf, nByte);

    if (!fin)
        throw std::runtime_error("readLE: failed to read from file");

    uint64_t val = 0;
    for (size_t i = 0; i < nByte; ++i) {
        val |= static_cast<uint64_t>(static_cast<unsigned char>(buf[i])) << (8 * i);
    }
    return val;
}

// 读取 nByte（1~8）的二进制大端整数
inline uint64_t readBE(std::ifstream* fin, size_t nByte) {
    if (nByte == 0 || nByte > 8)
        throw std::invalid_argument("readBE: nByte must be 1~8");
    if (!fin)
        throw std::runtime_error("readBE: failed to read from file");
    uint64_t result = 0;
    for (size_t i = 0; i < nByte; ++i) {
        uint8_t byte;
        fin->read(reinterpret_cast<char*>(&byte), 1);
        result = (result << 8) | byte;  // 大端：先读的放高位
    }
    return result;
}

inline void printBinary(uint64_t value) {
    std::bitset<64> bits(value);  // 64位二进制表示
    std::cout << bits << std::endl;
}
